#!/bin/bash


install_git(){
	if which opkg;then
		# opkg update
		# opkg install git
		opkg update
		# opkg remove git
		opkg install git-http
		opkg install ca-bundle
	elif which apt;then
		echo '[info] maybe need root'
		apt update
		apt install git
	fi
}


if ! which git;then
	
	install_git
	if ! which git;then
		echo "[E] install git failed"
	fi
fi



(
 ###### settings
	REPO_URL="https://github.com/cysk003/Yoursmile7_TVBox"

	# FROM_='https://agit.ai/Yoursmile7/TVBox/raw/branch/master/'
	FROM_='https?://[^/]+/Yoursmile7/TVBox/raw/branch/master/'
	#TO_='http://server.lan:9966/jsons/Yoursmile7_TVBox/'
	#TO_="http://server2.lan:81/tvbox_vod/Yoursmile7_TVBox/"
	TO_="http://server22.lan:9966/box1_more_and_more/tvbox_vod/Yoursmile7_TVBox/"
 ############ end








	init_file="${service_name}.inited.txt"

	service_name="$(basename "$0")"

	repo="Yoursmile7_TVBox"

	dst="$(dirname "$0")/"
	# dst="/mnt/mmcblk2p4/"

	cd "$dst" # || echo "[E] $dst not exist" && exit 1


	if [ "$1" == "clone" ];then
		if [ ! -d "$repo" ];then
			git clone "$REPO_URL" "$repo"
		else
			if git clone "$REPO_URL" "tmp_repo";then
				rm -rf "$repo"
				mv "tmp_repo" "$repo"
			elif [ -d "$repo/.git" ];then
				(
					cd "$repo"
					git  reset --hard HEAD
					git  status
				)
			fi

			rm "$init_file" 2>/dev/null
		fi
	fi

	if [ ! -d "$repo" ];then
		echo "[E] can't find repo : $repo"
		exit 1
	fi

	cd "$repo"

	check(){
		# 获取远程仓库的信息
		git fetch --quiet

		# 比较本地当前分支与远程分支的差异
		upstream_commit=$(git rev-parse @{u})
		local_commit=$(git rev-parse HEAD)

		# 判断本地是否已经是最新的
		if [[ $upstream_commit == $local_commit ]]; then
			echo "已是最新提交"
			return 1
		else
			echo "有新提交，执行git pull"
			git reset --hard HEAD
			git pull --quiet
			return 0
		fi
	}

	do_it(){
		local from_ to_
		from_="$FROM_"
		to_="$TO_"

		rm "1.json" 2>/dev/null
		echo "  before:"
		grep   -r -iE -l "$from_" . | grep -vE "^\.git/"
		grep   -r -iE -l "$from_" . | grep -vE "^\.git/"  | xargs sed -i -E "s@${from_}@${to_}@g"
		sed -i "s@玩偶哥哥@__@g" XC.json
		sed -i "s@csp_WoGG@__@g" XC.json

		

		echo "------------------"
		ln -s XC.json 1.json
		#echo "  after:"
		#grep   -r -iE -l "$from_" .
	}

	is_first(){
		if [ ! -e "../$init_file" ];then
			return 0
		fi
		return 1	
	}

	init_it(){
		date > "../$init_file"
	}


	if is_first;then
		echo "[info] 1st"
		do_it
		init_it
	elif check;then
		echo "[info] update"
		do_it
	elif [ "$1" == "url" ] ;then
		echo "[info] transform url"
		do_it
	fi

)


